package com.bootdo.program.wallpaper.controller;

import java.math.BigDecimal;
import java.util.*;

import cn.hutool.core.date.DateUtil;
import com.bootdo.common.controller.BaseController;
import com.bootdo.common.utils.StringUtils;
import com.bootdo.common.utils.seq.GenerateSequenceUtil;
import com.bootdo.program.wallpaper.domain.*;
import com.bootdo.program.wallpaper.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.Query;
import com.bootdo.common.utils.R;

/**
 * 用户结算账单
 *
 * @author guoyunfei
 * @email 2549789059@qq.com
 * @date 2021-10-30 23:38:53
 */

@Controller
@RequestMapping("/wallpaper/settlemenbill")
public class SettlemenbillController extends BaseController {
	@Autowired
	private SettlemenbillService settlemenbillService;

	@Autowired
	private AppConnectService appConnectService;

	@Autowired
	private BzTalentService bzTalentService;

	@Autowired
	private BzBaseinfoService bzBaseinfoService;

	@Autowired
	private BalanceRecordService balanceRecordService;

	@Autowired
	private DistributionProfitService distributionProfitService;

	@Autowired
	private WalletDetailsService walletDetailsService;

	@Autowired
	private WithdrawalDetailsService withdrawalDetailsService;

	@Autowired
	private BzConfigService bzConfigService;


	@GetMapping()
	@RequiresPermissions("wallpaper:settlemenbill:settlemenbill")
	String Settlemenbill(Model model){
		List<BzConfigDO> platform_type = bzConfigService.getType("platform_type");
		model.addAttribute("platform_type",platform_type);
		return "wallpaper/settlemenbill/settlemenbill";
	}


	@ResponseBody
	@GetMapping("/getCount")
	public R getCount(){
		Map<String, Object> params = new HashMap<>();
		params.put("status",1);
		//params.put("appid",queryAppid());

		int count1 = settlemenbillService.count(params);
		params.put("status",2);
		int count2 = settlemenbillService.count(params);
		params.put("status",3);
		int count3 = settlemenbillService.count(params);

		return  R.ok().put("count1","待入账("+count1+")").put("count2","已入账("+count2+")").put("count3","入账失败("+count3+")");
	}

	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("wallpaper:settlemenbill:settlemenbill")
	public PageUtils list(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		List<SettlemenbillDO> settlemenbillList = settlemenbillService.list(query);

		int total = settlemenbillService.count(query);
		PageUtils pageUtils = new PageUtils(settlemenbillList, total);
		return pageUtils;
	}

	@GetMapping("/add")
	@RequiresPermissions("wallpaper:settlemenbill:add")
	String add(Model model){
		List<BzConfigDO> platform_type = bzConfigService.getType("platform_type");
		model.addAttribute("platform_type",platform_type);
		return "wallpaper/settlemenbill/add";
	}

	@GetMapping("/addWallet")
	@RequiresPermissions("wallpaper:settlemenbill:add")
	String addWallet(Model model){
		List<BzConfigDO> platform_type = bzConfigService.getType("platform_type");
		model.addAttribute("platform_type",platform_type);
		return "wallpaper/settlemenbill/addWallet";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("wallpaper:settlemenbill:edit")
	String edit(@PathVariable("id") Long id,Model model){
		SettlemenbillDO settlemenbill = settlemenbillService.get(id);

		AppConnectDO connectDO = appConnectService.getByUserId(settlemenbill.getUserid());

		if(null != connectDO){
			settlemenbill.setUserName(connectDO.getNickName());
		}
		model.addAttribute("settlemenbill", settlemenbill);
		return "wallpaper/settlemenbill/edit";
	}

	@GetMapping("/editWallet/{id}")
	@RequiresPermissions("wallpaper:settlemenbill:edit")
	String editWallet(@PathVariable("id") Long id,Model model){
		SettlemenbillDO settlemenbill = settlemenbillService.get(id);

		BzTalentDO bzTalentDO = bzTalentService.getByUserId(settlemenbill.getUserid());
		if(null != bzTalentDO){
			settlemenbill.setUserName(bzTalentDO.getNickname());
		}
		model.addAttribute("settlemenbill", settlemenbill);
		return "wallpaper/settlemenbill/editWallet";
	}

	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("wallpaper:settlemenbill:add")
	public R save( SettlemenbillDO settlemenbill){
		if(settlemenbillService.save(settlemenbill)>0){
			return R.ok();
		}
		return R.error();
	}
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("wallpaper:settlemenbill:edit")
	@Transactional
	public R update( SettlemenbillDO settlemenbill){

		try {
			SettlemenbillDO settlemenbillDO = settlemenbillService.get(settlemenbill.getId());

			String userid = settlemenbillDO.getUserid();
			Date sTime = settlemenbillDO.getSettlementTime();

			settlemenbillDO.setUpdateUser(getUserId());
			settlemenbillDO.setPaymentTime(new Date());
			settlemenbillDO.setStatus(settlemenbill.getStatus());
			int update = settlemenbillService.update(settlemenbillDO);

			if(update > 0){

				SettlemendaysBillDO settlemenDays = new SettlemendaysBillDO();
				settlemenDays.setStatus(settlemenbillDO.getStatus());
				settlemenDays.setUpdateUser(getUserId());
				settlemenDays.setSettlementTime(settlemenbillDO.getSettlementTime());
				settlemenDays.setUserid(settlemenbillDO.getUserid());

				if(1 == settlemenbillDO.getDtype()){
					//修改广告收益
					settlemenbillService.updateStatus(3,DateUtil.format(sTime,"yyyy-MM-dd HH:mm:ss"),userid,settlemenbill.getSettlemantPlatform());
				}else{
					//修改分销收益
					distributionProfitService.updateStatus(3,DateUtil.format(sTime,"yyyy-MM-dd HH:mm:ss"),userid,settlemenbill.getSettlemantPlatform());
				}
				settlemenDays.setDtype(settlemenbillDO.getDtype());
				//修改日结算单状态
				settlemenbillService.updateSettlemenStatus(settlemenDays);


			}else{
				return R.error("打款失败");
			}
		}catch (Exception e){
			return R.error("打款失败");
		}
		return R.ok();
	}

	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("wallpaper:settlemenbill:remove")
	public R remove( Long id){
		if(settlemenbillService.remove(id)>0){
			return R.ok();
		}
		return R.error();
	}

	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("wallpaper:settlemenbill:batchRemove")
	public R remove(@RequestParam("ids[]") Long[] ids){
		settlemenbillService.batchRemove(ids);
		return R.ok();
	}

	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/addSettlemenbill")
	@RequiresPermissions("wallpaper:settlemenbill:add")
	public R addSettlemenbill(String sTime,Integer settlemantPlatform) throws Exception {

		String message = getMessage();
		if(null != message){
			return R.error(message);
		}

		if(StringUtils.isEmpty(sTime)){
			return R.error("请选择结算月份");
		}

		if(null == settlemantPlatform){
			return R.error("请选择结算平台");
		}

		//获取结算数据
		SettlemenbillDO settlemenbill = new SettlemenbillDO();
		settlemenbill.setStartTime(sTime + "-01 00:00:00");
		settlemenbill.setSettlemantPlatform(settlemantPlatform);

		//查询该时间段内是否存在结算单
		int count = settlemenbillService.selectCount(settlemenbill);
		if(count > 0){
			return R.error("当月已生成结算单，请勿重新生成！");
		}

		List<SettlemenbillDO> list = balanceRecordService.statisticsSettlement(settlemenbill);
		if(list.size() == 0 ){
			return R.error("暂无结算信息");
		}

		//需要修改
		BzBaseinfoDO baseinfo = bzBaseinfoService.getByPlatformType(settlemantPlatform);
		if(null == baseinfo ){
			return R.error("获取提现技术费失败，请先配置提现技术费");
		}

		if(null == baseinfo.getPlatformRate() ){
			return R.error("获取提现技术费失败，请先配置提现技术费");
		}

		if(null == baseinfo.getTaxrate() ){
			return R.error("获取税率失败,请先配置税率");
		}

		//平台抽佣百分比
		BigDecimal divide = baseinfo.getPlatformRate().divide(new BigDecimal("100"));
		//平台税百分比
		BigDecimal taxrate = baseinfo.getTaxrate().divide(new BigDecimal("100"));
		int i = settlemenbillService.addSettlemenbill(list,sTime,divide,taxrate,settlemantPlatform);
		if(i > 0){
			return R.ok();
		}
		return R.error("生成结算单失败");
	}

	/**
	 * 钱包入账，批量，按照月份入账
	 */
	@ResponseBody
	@PostMapping("/addWalletInfo")
	@RequiresPermissions("wallpaper:settlemenbill:add")
	public R addWalletInfo(String sTime,Integer settlemantPlatform) throws Exception {

		String message = getMessage();
		if(null != message){
			return R.error(message);
		}

		if(StringUtils.isEmpty(sTime)){
			return R.error("请选择入账月份");
		}

		if(null == settlemantPlatform){
			return R.error("请选择入账平台");
		}
		String days = DateUtil.format(new Date(), "dd");

		String time = sTime + "-"+days+" 00:00:00";

		int i = settlemenbillService.addWalletInfo(time,settlemantPlatform);
		if(i == -1){
			return R.error("没有可入账的信息");
		}
		if(i > 0){
			return R.ok("入账成功");
		}

		return R.error("入账失败");
	}

	/**
	 * 钱包入账，单个
	 */
	@ResponseBody
	@PostMapping("/updateWallet")
	@RequiresPermissions("wallpaper:settlemenbill:edit")
	public R updateWallet(SettlemenbillDO settlemenbillDO) throws Exception {

		String message = getMessage();
		if(null != message){
			return R.error(message);
		}

		if(null == settlemenbillDO.getId()){
			return R.error("参数获取错误");
		}

		int i = settlemenbillService.updateWalletInfo(settlemenbillDO);
		if(i == -1){
			return R.error("没有可入账的信息");
		}
		if(i > 0){
			return R.ok("入账成功");
		}

		return R.error("入账失败");
	}


	/**
	 * 数据补录
	 */
	@PostMapping( "/editWalletBu")
	@ResponseBody
	@RequiresPermissions("wallpaper:settlemenbill:edit")
	public R editWalletBu(Long id) throws InterruptedException {

		SettlemenbillDO settlemenbillDO = settlemenbillService.get(id);
		//添加余额记录
		walletDetailsService.addWallet(settlemenbillDO.getUserid(),settlemenbillDO.getAmount(),1,1);
		Thread.sleep(1000);
		walletDetailsService.addWallet(settlemenbillDO.getUserid(),settlemenbillDO.getAmount(),1,2);
		//添加提现记录
		WithdrawalDetailsDO withdrawalDetailsDO = new WithdrawalDetailsDO();
		withdrawalDetailsDO.setUserId(settlemenbillDO.getUserid());
		withdrawalDetailsDO.setMoney(settlemenbillDO.getAmount());
		withdrawalDetailsDO.setActualMoney(settlemenbillDO.getActualPaymentAmount());
		withdrawalDetailsDO.setApplyTime(new Date());
		withdrawalDetailsDO.setAuditTime(new Date());
		withdrawalDetailsDO.setPayTime(new Date());
		withdrawalDetailsDO.setStatus(2);
		withdrawalDetailsDO.setPlatformRate(new BigDecimal("0.5"));
		withdrawalDetailsDO.setTaxrate(new BigDecimal("6"));
		withdrawalDetailsDO.setFlowNo("W"+GenerateSequenceUtil.generateSequenceNo());
		withdrawalDetailsService.save(withdrawalDetailsDO);
		return R.ok();
	}

}
